import 'package:chathouse/constant/app_constant.dart';
import 'package:chathouse/constant/my_color.dart';
import 'package:chathouse/model/response_bean.dart';
import 'package:chathouse/pages/login/forget_password_page.dart';
import 'package:chathouse/pages/login/register_page.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:chathouse/util/log.dart';
import 'package:chathouse/widgets/base_appbar.dart';
import 'package:chathouse/widgets/form_widgets/form_widgets.dart';
import 'package:chathouse/widgets/my_drop_down_widget.dart';
import 'package:chathouse/widgets/my_input_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../net/Apis.dart';
import '../../public/Global.dart';
import '../../public/Obj.dart';
import '../../util/SpUtil.dart';
import '../../util/font_utils.dart';
import '../client/client_root_container.dart';
import '../expert/expert_root_page.dart';

//登入
class LoginPage extends StatefulWidget {
  LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String areaSelectedValue = "0";
  List<MyDropDownBean> areas = [
    MyDropDownBean("0", "+852"),
    MyDropDownBean("1", "+86"),
  ];
  bool rememberMe = false;

  TextEditingController phoneTextEditingController = TextEditingController();
  TextEditingController emailTextEditingController = TextEditingController();
  TextEditingController pwdTextEditingController = TextEditingController();
  bool canLogin = false;

  @override
  void initState() {
    super.initState();
    phoneTextEditingController.addListener(() {
      setLoginBtnEnable();
    });
    emailTextEditingController.addListener(() {
      setLoginBtnEnable();
    });
    pwdTextEditingController.addListener(() {
      setLoginBtnEnable();
    });
    // phoneTextEditingController.text = "19928459816";
    // pwdTextEditingController.text = "123456";
    // areaSelectedValue = "1";
    rememberMe = SpUtil.getBool(
    AppConstant.userRole == UserRole.c ?
    AppConstant.cRememberMe:
    AppConstant.bRememberMe,
    );
    if(!rememberMe) return;
    areaSelectedValue = SpUtil.getString(
      AppConstant.userRole == UserRole.c ?
      AppConstant.cLoginArea:
      AppConstant.bLoginArea,
    );
    if(areaSelectedValue.isEmpty) areaSelectedValue = "0";
    phoneTextEditingController.text = SpUtil.getString(
      AppConstant.userRole == UserRole.c ?
      AppConstant.cLoginPhone:
      AppConstant.bLoginPhone, 
    );
    emailTextEditingController.text = SpUtil.getString(
      AppConstant.userRole == UserRole.c ?
      AppConstant.cLoginEmail:
      AppConstant.bLoginEmail
    );
    pwdTextEditingController.text = SpUtil.getString(
      AppConstant.userRole == UserRole.c ?
      AppConstant.cLoginPwd:
      AppConstant.bLoginPwd
    );
  }

  @override
  void dispose() {
    super.dispose();
    phoneTextEditingController.dispose();
    emailTextEditingController.dispose();
    pwdTextEditingController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(leading: Container()),
      body: ListView(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                AppConstant.userRole == UserRole.c ? "用戶登入或註冊" : "服務專家登入或註冊",
                textAlign: TextAlign.center,
                style: getTextStyle(32.sp,
                    fontType: FontType.BOLD,
                    color: AppConstant.userRole == UserRole.c
                        ? MyColors.brow_2551520
                        : MyColors.green_69157154),
              ).setContainer(margin: EdgeInsets.only(top: 52.w)),
              Row(
                children: [
                  MyDropDownWidget(areaSelectedValue, areas, (val) {
                    areaSelectedValue = val;
                    print('onchange areaSelectedValue: '+areaSelectedValue);
                  },
                    placeholder: "test",
                  ).setContainer(width: 100.w),
                  Expanded(
                      child: MyInputWidget(
                    placeholder: "電話號碼",
                    controller: phoneTextEditingController,
                  ).setContainer(margin: EdgeInsets.only(left: 6.w)))
                ],
              ).setContainer(margin: EdgeInsets.only(top: 28.w)),
              MyInputWidget(
                leftIcon: Icon(
                  Icons.email_outlined,
                  size: 24.w,
                  color: MyColors.gary_155155155,
                ).setContainer(margin: EdgeInsets.only(right: 4.w)),
                placeholder: "電郵登入(必填)＊",
                controller: emailTextEditingController,
              ).setContainer(margin: EdgeInsets.only(top: 28.w)),
              MyInputWidget(
                title: "密碼",
                placeholder: "",
                obscureText: true,
                isShoweYe: true,
                controller: pwdTextEditingController,
              ).setContainer(margin: EdgeInsets.only(top: 14.w)),
              Row(
                children: [
                  Checkbox(
                      value: rememberMe,
                      onChanged: (bool? b){
                        setState((){
                          rememberMe = b!;
                        });
                      }),
                  InkWell(
                    onTap: (){
                      setState(() {
                        rememberMe = !rememberMe;
                      });
                    },
                      child: Text("記住我", style: getTextStyle(16.sp))),
                ],
              ).setContainer(margin: EdgeInsets.only(top: 14.w)),
              Text(
                "忘記密碼",
                style: getTextStyle(18.sp,
                    color: MyColors.blue_5674190, fontType: FontType.DEFAULT),
              )
                  .setContainer(margin: EdgeInsets.only(top: 10.w))
                  .setOnClickListener(() {
                Get.to(const ForgetPasswordPage());
              }),
              FormWidgets.getTextButton(
                      "登入",
                      AppConstant.userRole == UserRole.c
                          ? MyColors.brow_2551520
                          : MyColors.green_69157154,
                      enable: canLogin)
                  .setContainer(
                      margin:
                          EdgeInsets.only(left: 44.w, right: 44.w, top: 32.w))
                  .setOnClickListener(() {
                loginAction();
              }),
              FormWidgets.getTextButton(
                      "註冊",
                      AppConstant.userRole == UserRole.c
                          ? MyColors.red_2166474
                          : MyColors.blue_6978157)
                  .setContainer(
                      margin:
                          EdgeInsets.only(left: 44.w, right: 44.w, top: 24.w))
                  .setOnClickListener(() {
                Get.to(RegisterPage());
              }),
            ],
          ).setContainer(padding: EdgeInsets.symmetric(horizontal: 28.w))
        ],
      ).setContainer(color: Colors.white),
    );
  }

  void setLoginBtnEnable() {
    setState(() {
      canLogin = phoneTextEditingController.text.isNotEmpty &&
              emailTextEditingController.text.isNotEmpty &&
          pwdTextEditingController.text.isNotEmpty;
    });
  }

  void loginAction() {
    if (!canLogin) return;
    print('loginAction areaSelectedValue: '+areaSelectedValue);
    String area = areas
        .firstWhere((element) {
          return areaSelectedValue == element.value;
        })
        .name
        .substring(1);
    String userName = phoneTextEditingController.text.isNotEmpty
        ? (area + phoneTextEditingController.text)
        : emailTextEditingController.text;
    var params = {
      "mark": 1, //0:管理端;1:app端
      "password": pwdTextEditingController.text,
      "username": userName,
    };
    FocusManager.instance.primaryFocus?.unfocus();
    Obj.showLoading();
    ResponseBean result;

    LogUtil.d("id:${SpUtil.getString(AppConstant.jPushRegistrationID)}");
    Apis.login(params, queryParameters: {
      "Identity": AppConstant.userRole == UserRole.c ? "1" : "2",
      "registrationId": SpUtil.getString(AppConstant.jPushRegistrationID)
    })
        .then((response) => {
              Obj.dismissLoading(),
              result = ResponseBean.fromJson(response?.data ?? {}),
              if (result.isRequestSuccess)
                {
                  SpUtil.putBool(
                      AppConstant.userRole == UserRole.c ?
                      AppConstant.cRememberMe:
                      AppConstant.bRememberMe, rememberMe
                  ),
                  SpUtil.putString(
                    AppConstant.userRole == UserRole.c ?
                    AppConstant.cLoginArea:
                    AppConstant.bLoginArea, areaSelectedValue),
                  SpUtil.putString(
                    AppConstant.userRole == UserRole.c ?
                    AppConstant.cLoginPhone:
                    AppConstant.bLoginPhone
                    // AppConstant.loginPhone
                    , 
                    phoneTextEditingController.text),
                  SpUtil.putString(
                    AppConstant.userRole == UserRole.c ?
                    AppConstant.cLoginEmail:
                    AppConstant.bLoginEmail
                    // AppConstant.loginEmail
                    , 
                    emailTextEditingController.text),
                  SpUtil.putString(
                    AppConstant.userRole == UserRole.c ?
                    AppConstant.cLoginPwd:
                    AppConstant.bLoginPwd
                    // AppConstant.loginEmail
                    ,  
                    pwdTextEditingController.text),

                  SpUtil.putString(Keys.token, response?.data[Keys.token]),
                  AppConstant.token = response?.data[Keys.token],
                  Get.offAll(AppConstant.userRole == UserRole.c
                      ? const ClientRootPage()
                      : const ExpertRootPage()),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }
}
